package com.pubinfo.passbook.api.controller.contract;

import com.alibaba.excel.EasyExcel;
import com.pubinfo.passbook.api.eip.UserInfoService;
import com.pubinfo.passbook.api.service.CompanyExcelService;
import com.pubinfo.passbook.common.entity.TContractBase;
import com.pubinfo.passbook.common.enums.ContractStatusEnum;
import com.pubinfo.passbook.common.handler.excel.CustomSheetWriteHandler;
import com.pubinfo.passbook.common.model.dto.contract.ContractAdoptParam;
import com.pubinfo.passbook.common.model.dto.contract.ContractIdParam;
import com.pubinfo.passbook.common.model.dto.contract.ContractListParam;
import com.pubinfo.passbook.common.model.http.eip.UserInfo;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import com.pubinfo.passbook.common.model.vo.base.MyPage;
import com.pubinfo.passbook.common.model.vo.base.ResultCode;
import com.pubinfo.passbook.common.model.vo.contract.ContractBaseExcel;
import com.pubinfo.passbook.common.model.vo.contract.ContractDetailInfoVo;
import com.pubinfo.passbook.common.model.vo.contract.ContractDetailVo;
import com.pubinfo.passbook.common.service.contract.TContractBaseService;
import com.pubinfo.passbook.common.service.contract.impl.TContractSyncServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

@Slf4j
@RestController
@Api(tags = "QGPB-合同清洗")
@RequestMapping(value = "contract-trial")
public class ContractBaseTrialController {
    
    @Autowired
    CompanyExcelService companyExcelService;
    @Resource
    private UserInfoService userInfoService;
    
    @Resource
    private TContractBaseService contractBaseService;
    
    @Resource
    private TContractSyncServiceImpl tContractSyncService;
    
    @PostMapping("list")    
    @ApiOperation(value = "查询列表数据")
    public JsonResult<MyPage<TContractBase>> list(@RequestBody ContractListParam param) {
        //  param.setContractType(ContractTypeEnum.TRIAL);
        UserInfo userInfo = userInfoService.getCurrentUserInfo();
        param.setRoleCode(userInfo.getRoleCode());
        param.setAcct(userInfoService.getCurrentAcct());
        param.setOrgId(userInfo.getOrgId());
    
        return JsonResult.success(new MyPage(contractBaseService.selectContractList(param)));
    }

    @PostMapping("info")
    @ApiOperation(value = "合同信息")
    public JsonResult<ContractDetailInfoVo> info(@RequestBody ContractIdParam param) {
        return JsonResult.success(contractBaseService.contractInfo(param));
    }

    @PostMapping("detail")
    @ApiOperation(value = "合同详情")
    public JsonResult<ContractDetailVo> detail(@RequestBody ContractIdParam param) {
        return JsonResult.success(contractBaseService.contractDetail(param));
    }

    @PostMapping("adopt")
    @ApiOperation(value = "合同认领")
    public JsonResult<ResultCode> adopt(@RequestBody ContractAdoptParam param) {
        UserInfo userInfo = userInfoService.getCurrentUserInfo();
        param.setRoleCode(userInfo.getRoleCode());
        return contractBaseService.contractAdopt(userInfoService.getCurrentAcct(), param);
    }

    @PostMapping("close")
    @ApiOperation(value = "合同关闭")
    public JsonResult<ResultCode> close(@RequestBody ContractIdParam param) {
      return contractBaseService.contractClose(userInfoService.getCurrentAcct(), param);
    }

    @GetMapping("sync")
    @ApiOperation(value = "同步合同")
    public JsonResult<ResultCode> sync() {
        tContractSyncService.syncContract(null);
//        tContractSyncService.syncContractCostItems();
//        tContractSyncService.syncContractProject();
        return new JsonResult<>();
    }

    @GetMapping("sync-wbs")
    @ApiOperation(value = "同步合同WBS项目")
    public JsonResult<ResultCode> syncWbs() {
//        tContractSyncService.syncContract();
        tContractSyncService.syncContractProject();
        return new JsonResult<>();
    }
    
    @GetMapping("sync-wbs1")
    @ApiOperation(value = "同步合同WBS项目成本")
    public JsonResult<ResultCode> syncWbs1() {
//        tContractSyncService.syncContract();
        tContractSyncService.syncContractCostItems();
        return new JsonResult<>();
    }
    
    @GetMapping("sync-not-clear")
    @ApiOperation(value = "同步未清项目")
    public JsonResult<ResultCode> syncNotClear() {
        tContractSyncService.syncProjectNotClear();
//        tContractSyncService.syncContractCostItems();
//        tContractSyncService.syncContractProject();
        return new JsonResult<>();
    }
    
    @PostMapping("importContractStatus")
    @ApiOperation(value = "导入合同状态")
    public JsonResult<Boolean> importContractStatus(@RequestBody MultipartFile file) {
        
        return JsonResult.success(companyExcelService.importContractStatus(userInfoService.getCurrentAcct(), file));
    }
    
    @PostMapping("importContractLocalStatus")
    @ApiOperation(value = "导入本地合同状态")
    public JsonResult<Boolean> importContractLocalStatus(@RequestBody MultipartFile file, HttpServletResponse response) {
        
        return JsonResult.success(companyExcelService.importContractLocalStatus(response, userInfoService.getCurrentAcct(), file));
    }
    
    @SneakyThrows
    @GetMapping("download/{status}")
    public void download(HttpServletResponse response, @PathVariable("status") ContractStatusEnum status) {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(status.name().toLowerCase() + "_contract", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    
        List<ContractBaseExcel> baseList = contractBaseService.listByStatus(status);
        List<String> includeColumnFiledNames = Arrays.asList(new String[]{"signDate", "endDate", "attachment", "contractPhone"});
        EasyExcel.write(response.getOutputStream(), ContractBaseExcel.class).excludeColumnFieldNames(includeColumnFiledNames).registerWriteHandler(new CustomSheetWriteHandler(baseList.size())).sheet(status.getDesc() + "的合同").doWrite(baseList);
    }
    
}
